var express = require('express');
var router = express.Router();
const posts = new require('../db/Posts');

/* post view */
router.get('/:id?/:action', function(req, res, next) {
  let partial = req.params.action.toLowerCase()
  if (Number(req.params.id)) {
    console.log(`Request action: ${partial} over post: ${req.params.id}`)
    posts.fetchByPK(['id', 'title', 'markdown', 'html', 'tags', 'status'], req.params.id, function (err, row) {
        if (err) {
          res.render('partial/error.njk', { error: err })
        } else {
          res.render(`partial/${partial}.njk`, { selected: row });
        }
      }
    )
  } else {
    res.render('partial/edit.njk');
  }
});

router.put('/', function(req, res, next) {
  let post = req.body
  post.html = 'HTML'  
  posts.update(post)
})

module.exports = router
